import {validateParameter} from "@/app/utils/validation";
import ToastUtil from "@/app/utils/toastUtil";
import cookie from "react-cookies";
import {inFifteenMinutes, Token, UserName} from "@/app/constants/authTokenConstants";
import {encodeToBase64} from "next/dist/build/webpack/loaders/utils";
import createAxiosClient from "@/app/utils/axiosRequest";

/**
 * 用户登录
 * @param username
 * @param password
 * @param setLoading
 * @constructor
 */
export default async function LoginService({username, password, setLoading}: any) {
    //axios统一配置中心
    const axiosInstance = createAxiosClient();
    /*参数验证*/
    if (!validateParameter({username, password})) {
        return false;
    }
    setLoading(true)
    await axiosInstance.post('/app/user/login',
        {
            username: username,
            password: password
        }, {
            headers: {
                'Content-Type': 'application/json'
            }
        }
    ).then(response => {
            const data = response.data;
            if (data.status) {
                ToastUtil(data.message, '☺️', "success")
                /*存储Token和UserName*/
                cookie.save(Token, data.data.token, {expires: inFifteenMinutes, path: '/'});
                cookie.save(UserName, encodeToBase64(username), {expires: inFifteenMinutes, path: '/'});/*Base64编码存储*/
                /*进入主页*/
                window.location.reload()
                return true;
            }
            ToastUtil(data.message, '😶', "error")
            cookie.remove(Token, {path: '/'})
            cookie.remove(UserName, {path: '/'})
            return false;
        }
    ).catch(error => {
            ToastUtil(error.message, '🤬', "error")
            return false;
        }
    ).finally(() => {
        /*更新Progress状态*/
        setLoading(false)
    })
}

/**
 * 手机号登录
 * @param mobile 手机号
 * @param code 验证码
 * @param setLoading 加载状态
 * @returns {Promise<boolean>}
 */
export async function MobileLoginService({mobile, code, setLoading}: any) {
    //axios统一配置中心
    const axiosInstance = createAxiosClient();
    /*参数验证*/
    if (!mobile || !code) {
        ToastUtil("手机号和验证码不能为空", '😶', "error");
        return false;
    }
    setLoading(true)
    await axiosInstance.post('/app/user/mobile/login',
        {
            mobile: mobile,
            code: code,
            deviceInfo: navigator.userAgent
        }, {
            headers: {
                'Content-Type': 'application/json'
            }
        }
    ).then(response => {
            const data = response.data;
            if (data.status) {
                ToastUtil(data.message, '☺️', "success")
                /*存储Token和UserName*/
                cookie.save(Token, data.data.token, {expires: inFifteenMinutes, path: '/'});
                cookie.save(UserName, encodeToBase64(data.data.username), {expires: inFifteenMinutes, path: '/'});/*Base64编码存储*/
                /*进入主页*/
                window.location.reload()
                return true;
            }
            ToastUtil(data.message, '😶', "error")
            cookie.remove(Token, {path: '/'})
            cookie.remove(UserName, {path: '/'})
            return false;
        }
    ).catch(error => {
            ToastUtil(error.message, '🤬', "error")
            return false;
        }
    ).finally(() => {
        /*更新Progress状态*/
        setLoading(false)
    })
}

/**
 * 发送验证码
 * @param mobile 手机号
 * @param type 验证类型 (login, register, reset)
 * @returns {Promise<boolean>}
 */
export async function SendVerificationCode({mobile, type = 'LOGIN'}: any) {
    //axios统一配置中心
    const axiosInstance = createAxiosClient();
    
    if (!mobile) {
        ToastUtil("手机号不能为空", '😶', "error");
        return false;
    }
    
    return await axiosInstance.post('/app/user/verification/code',
        {
            mobile: mobile,
            type: type
        }, {
            headers: {
                'Content-Type': 'application/json'
            }
        }
    ).then(response => {
        const data = response.data;
        if (data.status) {
            ToastUtil(data.message || "验证码已发送", '☺️', "success");
            return true;
        }
        ToastUtil(data.message, '😶', "error");
        return false;
    }).catch(error => {
        ToastUtil(error.message, '🤬', "error");
        return false;
    });
}